package com.lzq.badminton.security;

import cn.hutool.core.util.ObjectUtil;
import com.lzq.badminton.entity.User;
import com.lzq.badminton.entity.UserRole;
import com.lzq.badminton.service.RoleService;
import com.lzq.badminton.service.UserRoleService;
import com.lzq.badminton.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
public class WxAuthenticationManager implements AuthenticationManager {

    @Resource
    private UserService userService;

    @Autowired
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        WxAuthenticationToken token = null;
        if (authentication instanceof WxAuthenticationToken) {
            token = (WxAuthenticationToken) authentication;
        }
        User user = userService.getByOpenId(token.getOpenId());
        String name = token.getName();
        String avatar = token.getAvatar();
        String phone = token.getPhone();


        System.out.println("openId111:" + token.getOpenId());
        //注册
        if (ObjectUtil.isEmpty(user)) {
            // 注册账号
            System.out.println("###############");
            System.out.println("openId:" + token.getOpenId());
            user = new User();

            user.setOpenid(token.getOpenId());
            user.setName(name);
            user.setAvatar(avatar);
            user.setPhone(phone);
            user.setCreateTime(LocalDateTime.now());
            userService.save(user);
            UserRole userRole = new UserRole(user.getId(), 5L, 1);
            userRoleService.save(userRole);
        }

        // 登录
        Long userId = user.getId();
        // 获取权限
        List<String> roleKeyList = roleService.selectRoleKeyByUserId(userId, 1);
        List<SimpleGrantedAuthority> authorityList = roleKeyList
                .stream()
                .map(roleKey -> new SimpleGrantedAuthority("ROLE_" + roleKey))
                .collect(Collectors.toList());


        return new WxAuthenticationToken(token.getOpenId(), userId, authorityList);
    }
}

